#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <pthread.h>
#include <string>
#include <cstdio>
#include <cstring>
#include <functional>
namespace threadModlue
{
    static uint32_t number = 1;
    using func_t = std::function<void()>;
    class Thread
    {

    public:
        Thread(func_t fun)
            : _func(fun),
              _tid(0),
              _isdetach(false),
              _isrunning(false),
              _res(nullptr)
        {
            _name = "thread-" + std::to_string(number++);
        }
        std::string GetStringOfName()
        {
            return _name;
        }
        void Detach()
        {
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            EnableDetach();
        }
        void EnableDetach()
        {
            _isdetach = true;
        }
        void EnanleRunning()
        {
            _isrunning = true;
        }
        static void *Routine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            if(self==nullptr)
            {
                return nullptr;
            }
            if (self->_isdetach)
                self->Detach();
            if (self->_isrunning)
                self->EnanleRunning();
            self->_func();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n != 0)
            {
                //std::cerr << "create thread error" << strerror(n) << std::endl;
                return false;
            }
            if (_isdetach)
                Detach();

            EnanleRunning();
            return true;
        }
        bool Stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    //std::cerr << "Stop thread error" << strerror(n) << std::endl;
                    return false;
                }
                _isrunning = false;
                
            }
            return true;
        }
        bool join()
        {
            int n = pthread_join(_tid, &_res);
            if (n != 0)
            {
                //std::cerr << "join thread error" << strerror(n) << std::endl;
                return false;
            }
            return true;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *_res;
        func_t _func;
    };
}

#endif